Page({
  data: {
    phone: '',
    password: ''
  },

  // 输入手机号
  onPhoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  // 输入密码
  onPasswordInput(e) {
    this.setData({
      password: e.detail.value
    })
  },

  // 登录
  async login() {
    const { phone, password } = this.data
    if (!phone || !password) {
      wx.showToast({
        title: '请输入手机号和密码',
        icon: 'none'
      })
      return
    }

    try {
      const res = await wx.request({
        url: 'http://localhost:3000/api/test/users/login',
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: {
          phone,
          password
        },
        success: (response) => {
          console.log('请求成功:', response);
          const { data, statusCode } = response;
          
          if (statusCode === 200 && data && data.token) {
            wx.setStorageSync('token', data.token);
            wx.setStorageSync('userInfo', data.userInfo);
            
            wx.switchTab({
              url: '/pages/user/user'
            });
          } else {
            wx.showToast({
              title: data?.error || '登录失败',
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          console.error('请求失败:', error);
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
        }
      });
    } catch (error) {
      console.error('登录错误:', error);
      wx.showToast({
        title: '登录失败',
        icon: 'none'
      });
    }
  }
})